package tester.test.builder;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * This class will create and destroy elevators
 * @author cchan8
 *
 */
public class ElevatorBuilder {
	
	public static final ElevatorBuilder instance = new ElevatorBuilder();
	public static ElevatorBuilder getInstance(){
		return instance;
	}
	
	private ArrayList<Process> elevatorList;
	
	private ElevatorBuilder(){
		elevatorList = new ArrayList<Process>();
	}
	
	public void buildElevator(String filepath, String address, int port){
		String os = System.getProperty("os.name");
		System.out.println("OS Is : " + os);
		if (!os.contains("Linux")){
			return;
		}
		
		ProcessBuilder pd = new ProcessBuilder("./elevator", address, "" + port);
		pd.directory(new File(filepath));
		pd.redirectErrorStream();
		try {
			elevatorList.add(pd.start());
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void destroyAllElevatorProcess(){
		for(int i = 0; i < elevatorList.size(); i++){
			destroyElevatorProcess((byte)i);
		}
	}
	
	public void destroyElevatorProcess(byte elevatorId){
		
		String os = System.getProperty("os.name");
		System.out.println("OS Is : " + os);
		if (!os.contains("Linux")){
			return;
		}
		
		elevatorList.remove((int)elevatorId - 1).destroy();
	}
}
